package com.yu.newsSys.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

// 数据库工具类型
public class JDBCUtils {

    private static DataSource ds = null;
    // 初始化静态资源
    static {
        // 1.定义输入流
        InputStream is = null;
        try {
            is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            // 3.读取配置文件
            Properties properties = new Properties();
            properties.load(is);
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    // 关闭资源
    public static void close(ResultSet rs, Statement sta, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (sta != null) {
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
